package com.sh.caryr.erp.util;



public class TMUtility {

	/*private static String TOKEN_SERVER_URL = "https://oauth.taobao.com/token";
	private static String CALLBACK_URL = "http://baidu.com";
	private static String CODE = "lFJCPVeqlmHeJNy7C7Xaibmg29142"; // "重新获取code,然后用来申请access_token

	private static String API_SERVER_URL = "https://eco.taobao.com/router/rest";
	private static String APP_KEY = "24577316";
	private static String APP_SECRET = "f897c005c295271c9e607e666fdcc5a6";
	*//* 一年有效期2017-08-08 *//*
	private static String ACCESS_TOKEN = "6200f05b81fd8ZZd59b3a8a46a82fdeafbf066a7597d8ac2851740335";
	private static TaobaoClient client = new DefaultTaobaoClient(API_SERVER_URL, APP_KEY, APP_SECRET);
	private static String fommat = "yyyy-MM-dd HH:mm:ss";
	
	public static void main(String args[]) {
		//getProducts();
		//searchOrder(null,null,null,null,null);
	}

	public static void getProductAndMapping(HttpServletRequest request,List<Product> products, List<ProductMapping> productMappings) {
		List<Item> items = getProducts();
		parseProMappingsFromJD(request,items, productMappings);
		products.addAll(convert2Product(items, productMappings));
	}

	public static List<OrderSal> fetchOrders(String page, String pageSize, String startDate, String endDate) {
		List<OrderSal> soListERP  = null;
		List<Trade> trades = searchOrder(page, pageSize, null, startDate, endDate);
		if (trades != null) {
			soListERP  = convert2OrderSal(trades);
		}
		return soListERP;
	}
	
	private static List<OrderSal> convert2OrderSal(List<Trade> trades){
		List<OrderSal> soList = new ArrayList<OrderSal>();
		//-----Read ProductMappings
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("platForm", ERPConstants.PLATFORMS.get(ERPConstants.PLAT_TM));
		List<ProductMapping> proMapping = ProductMappingDao.findProductMappings(param, null);
		Map<String, Integer> proMappingM = new HashMap<String, Integer>();
		if (proMapping != null) {
			for (ProductMapping proMap : proMapping) {
				proMappingM.put(proMap.getPfProductId(), proMap.getProductId());
			}
		}

		for (int i = 0; i < trades.size(); i++) {
			//-----Convert OrderSal
			Trade trade = trades.get(i);
			List<Order> orders = trade.getOrders();
			for(Order order:orders){
				OrderSal so = new OrderSal();
				String status = null;
				so.setSalesChannel(ERPConstants.PLATFORMS.get(ERPConstants.PLAT_TM));
				so.setDataSource(ERPConstants.PLAT_TM);
				so.setCreatedAt(trade.getCreated());

				so.setRecName(trade.getReceiverName());
				so.setRecAddress(trade.getReceiverAddress());
				so.setRecTel(trade.getReceiverMobile());

				so.setNumber(""+order.getOid());
				so.setUpdateAt(trade.getModified());
				
				status = ERPConstants.EXT_SO_STAUTS_TM.get(order.getStatus());
				if(status!=null){
					so.setStatus(ERPConstants.EXT_SO_STAUTS_TM.get(order.getStatus())); 
				}
				so.setExpCompName(order.getLogisticsCompany());
				so.setExpNo(order.getInvoiceNo());
				so.setAmount(Float.parseFloat(order.getPayment()));
				
				com.sh.caryr.erp.pojo.OrderItem intItem = new com.sh.caryr.erp.pojo.OrderItem();
				Integer productId = proMappingM.get(""+order.getNumIid());
				if (productId == null || productId.intValue() == 0) {
					// return waring message;  取消订单重拍会生成订单号一样的订单
					// return null;   
					continue;
				}
				intItem.setProductId(productId);
				intItem.setProductCount(order.getNum());
				so.getOrderItems().add(intItem);
				soList.add(so);
			}
		}
		return soList;
		
	}
	
	private static List<Trade> searchOrder(String page, String pageSize, String state, String startDate,
			String endDate) {
		Date startDateD,endDateD ;
		long pageNoL = 0;
		long pageSizeL = 0;
		if (page == null || "".equals(page)) {
			pageNoL = 1L;
		}else{
			pageNoL = Long.parseLong(page);
		}
		
		if (pageSize == null || "".equals(pageSize)) {
			pageSizeL = 100L;
		}else{
			pageSizeL = Long.parseLong(pageSize);
		}
		
		
		startDateD = UtilityTool.parseDate(startDate,fommat);
		if (startDateD == null) {
			Calendar cal = Calendar.getInstance();
			cal.add(Calendar.MONTH, -3);
			startDateD = cal.getTime();
		}
		
		endDateD = UtilityTool.parseDate(endDate,fommat);
		if (endDateD == null) {
			Calendar cal = Calendar.getInstance();
			endDateD = cal.getTime();
		}
		
		 
		TradesSoldGetRequest req = new TradesSoldGetRequest();
		TradesSoldGetResponse rsp;
		req.setFields(
				"buyer_nick,title,type,created,sid,tid,status,"
				+ "payment,discount_fee,post_fee,total_fee,pay_time,end_time,"
				+ "modified,consign_time,received_payment,commission_fee,"
				+ "num_iid,num_iid,num,price,shipping_type,receiver_name,"
				+ "receiver_state,receiver_city,receiver_district,receiver_address,receiver_zip,"
				+ "receiver_mobile,receiver_phone,orders.title,orders.price,orders.num,orders.iid,"
				+ "orders.logistics_company,orders.invoice_no,orders.oid,orders.status,"
				+ "orders.num_iid,orders.sku_id,orders.refund_status,orders.status,"
				+ "orders.oid,orders.total_fee,orders.payment,orders.discount_fee,"
				+ "orders.sku_properties_name,orders.item_meal_name,orders.buyer_rate,"
				+ "orders.outer_iid,orders.outer_sku_id,orders.refund_id,trades.receiver_name, "
				+ "trades.receiver_state, trades.receiver_address, trades.receiver_zip,"
				+ " trades.receiver_mobile, trades.receiver_phone, trades.receiver_town, trades.status");
		
		req.setStartCreated(startDateD);
		req.setEndCreated(endDateD);
		req.setPageNo(pageNoL);
		req.setPageSize(pageSizeL);
		try {
			rsp = client.execute(req, ACCESS_TOKEN);
			return rsp.getTrades();
		} catch (ApiException e) {
			e.printStackTrace();
			return null;
		}
	}

	private static List<Item> getProducts() {
		ItemsOnsaleGetRequest req = new ItemsOnsaleGetRequest();
		req.setFields("approve_status,num_iid,title,nick,type,cid,num,"
				+ "valid_thru,list_time,price,has_discount,has_invoice,"
				+ "has_warranty,has_showcase,modified,delist_time,postage_id,"
				+ "seller_cids,outer_id,pic_url");
		req.setPageSize(100L);
		ItemsOnsaleGetResponse rsp;
		try {
			rsp = client.execute(req, ACCESS_TOKEN);
			//System.out.println(rsp.getBody());
			return rsp.getItems();
		} catch (ApiException e) {
			e.printStackTrace();
			return null;
		}
	}

	private static void parseProMappingsFromJD(HttpServletRequest request,List<Item> items, List<ProductMapping> productMappings) {
		String coco = request.getParameter("coco");
		String subcoco = request.getParameter("subcoco");
		ProductMapping productMapping;
		Item item;
		for (int i = 0; i < items.size(); i++) {
			productMapping = new ProductMapping();
			item = items.get(i);
			productMapping.setCoco(coco);
			productMapping.setSubcoco(subcoco);
			productMapping.setPfProductId("" + item.getNumIid());
			productMapping.setPfProName(item.getTitle());
			productMapping.setPlatForm(ERPConstants.PLATFORMS.get(ERPConstants.PLAT_TM));
			productMappings.add(productMapping);
		}
	}

	private static List<Product> convert2Product(List<Item> items, List<ProductMapping> productMappings) {
		List<Product> products = new ArrayList<Product>();
		for (Item item : items) {
			for (ProductMapping mapping : productMappings) {
				if (mapping.getPfProductId() != null && mapping.getPfProductId().equals(item.getNumIid().toString())) {
					Product product = new Product();
					// product.setSerialNo(item.getBarCode());
					product.setCoco(mapping.getCoco());
					product.setName(item.getTitle());
					product.setShortDesc(item.getTitle());
					// product.setBrand(item.getBrandName());
					// product.setCategory(ware.getCategoryId()+"");
					// product.setDescription(ware.getIntroduction());
					product.setImg(item.getPicUrl());
					product.setCostPrice(Float.parseFloat(item.getPrice().toString()));
					product.setSalePrice(Float.parseFloat(item.getPrice().toString()));
					product.setSalesChannel(ERPConstants.PLATFORMS.get(ERPConstants.PLAT_TM));
					product.setCreatedAt(new Date());
					products.add(product);
					break;
				}
			}
		}
		return products;
	}

	@SuppressWarnings("unused")
	private static class TM_ACCESS_TOKEN {
		public static void getAccessToken() {
			Map<String, String> props = new HashMap<String, String>();
			props.put("grant_type", "authorization_code");
			props.put("code", CODE);
			props.put("client_id", APP_KEY);
			props.put("client_secret", APP_SECRET);
			props.put("redirect_uri", CALLBACK_URL);
			props.put("view", "web");
			String s = "";
			try {
				s = WebUtils.doPost(TOKEN_SERVER_URL, props, 30000, 30000);
				System.out.println(s);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}*/
}
